package com.sjf.batch.controller;

import com.sun.deploy.net.URLEncoder;
import me.chyxion.xls.TableToXls;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * @author <huangtang>
 * @since 2022/1/25 16:28
 **/
@RestController
public class ExcelController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 统计分析结果导出
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/downloadPage")
    public void downloadPage ( String html , String xlsName , HttpServletResponse response , HttpServletRequest request ) throws UnsupportedEncodingException {

        response.setContentType ("application/vnd.ms-excel");
        response.setCharacterEncoding ("utf-8");

        String agent = request.getHeader ("USER-AGENT");
        if ( agent != null && agent.toLowerCase ().indexOf ("firefox") > 0 ) {
            String downloadFileName = "=?UTF-8?B?" + (new String (Base64.encodeBase64 (xlsName.getBytes ("UTF-8")) + ".xls")) + "?=";
            response.setHeader ("Content-Disposition" , "attachment;filename=" + downloadFileName);
        } else {
            response.setHeader ("Content-Disposition" , "attachment;filename=" + URLEncoder.encode (xlsName , "UTF-8") + ".xls");
        }

        try {
            ServletOutputStream out = response.getOutputStream ();
            TableToXls.process (html , out);
            out.close ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    @GetMapping(value = "/expiredTest")
    public void redisTest () {
        System.out.println ("redis访问记录");
        redisTemplate.opsForValue ().set ("test" , "值" , 50 , TimeUnit.SECONDS);
    }
}
